#coding=utf-8
from django.contrib.auth.decorators import login_required

from django.http import JsonResponse

from functools import wraps

from django.db import transaction




'''判断是否是登陆用户,返回视图'''
class LoginRequiredMinix(object):

    @classmethod
    def as_view(cls, **initkwargs):

        view = super().as_view(**initkwargs)

        return login_required(view)


# 自定义装饰器
def login_required_json(view_func):
    '''验证用户是否登陆,并返回ajax'''

    # 装饰器会修改方法的 __name__,有可能修改类视图中定义的请求方法的名字,造成请求分发失败
    # wraps装饰会保证被装饰的函数的__name__不会被改变.而且会保留原有的说明文档信息
    @wraps(view_func)
    def wrapper(request, *args, **kwargs):

        if not request.user.is_authenticated():

            return JsonResponse({'code': 1, 'message': '用户未登录'})

        else:
            # 登陆后返回相应视图
            return view_func(request, *args, **kwargs)

    return wrapper



'''自定义装饰器的拓展类, 判断是否登陆, 返回json'''
class LoginRequiredJSONMixin(object):
    # 重写as_view()
    @classmethod
    def as_view(cls, **initkwargs):

        view = super().as_view(**initkwargs)

        return login_required_json(view)




'''acomic装饰器: 提供数据库事务的功能'''
class TransactionAtomicMixin(object):


    @classmethod
    def as_view(cls, **initkwargs):

        view = super(TransactionAtomicMixin, cls).as_view(**initkwargs)

        return transaction.atomic(view)






